﻿<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class WeixinService extends MY_Controller {
	public function __construct(){
		parent::__construct();

		$this->load->helper(array('form','url'));
	}

    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }

	/**
     * weixin
     */
	public function getToken(){
        $url = $this->input->get("url");

        $APPID = "wx7090e27ffa3203e9";
        $APPSECRET = "384cec4e5c569d1b6f7445f9d15de2a7";

        // 获取access_token
        $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $APPID . "&secret=" . $APPSECRET;
        $res = $this->getSslPage($token_access_url); //获取文件内容或获取网络请求的内容
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
        //echo("access_token: <br/>");
        //var_export($result);
        $access_token = $result['access_token'];

        // 获取jsapi_ticket
        $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";

        $res = $this->getSslPage($ticket_url); //获取文件内容或获取网络请求的内容
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
        //echo("<br/>tickets: <br/>".$ticket_url."<br/>");
        //var_export($result);
        $ticket = $result['ticket'];

        $noncestr = $this->getRandChar(16);
        $timestamp = time();
        $parameters = array(
                                "noncestr" => $noncestr,
                                "jsapi_ticket" => $ticket,
                                "timestamp" => $timestamp,
                                "url" => $url
                            );
        ksort($parameters);

        $string1 = "";
        foreach ($parameters as $key => $val){
            $string1 .= $key."=".$val."&";
        }
        $string1 = substr($string1,0,-1);
        $signature = sha1($string1);

        echo(json_encode(array("appId"=>$APPID,"timestamp"=>$timestamp,"noncestr"=>$noncestr,"signature"=>$signature)));
	}

    /**
     * get https response
     * @param mixed $url
     * @return mixed
     */
    public function getSslPage($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}